package se.boars.dailystatistics;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {
	  	static InputStream is = null;
	    static JSONObject jObj = null;
	    static String json = "";
	
	public JSONObject getJSONObjectFromWeb(String url, List<NameValuePair> params) {
		
		try{
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(params));
			
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
		} catch (Exception e) {
			System.out.println("Http error: " + e);
		}
		
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			
			while((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			
			is.close();
			json = sb.toString();
			Log.e("JSON", json);
		} catch (Exception e) {
			System.out.println("StringReader error: " + e);
		}
		
		try {
			jObj = new JSONObject(json);
		} catch(Exception e) {
			System.out.println("JSON Error: " + e);
		}
		
		return jObj;
	}
}
